<template>
  <div
    class="form"
    :style="{
      '--theme-color': settings.themeColor,
      '--active-color': settings.activeColor,
    }"
  >
    <div class="form-top">
      <!-- 返回 | 标题 -->
      <div class="form-top-lt">
        <p>
          <span @click="goBack"><i class="el-icon-back"></i></span>
        </p>
      </div>
      <!-- tab -->
      <div class="form-top-ct">
        <ul class="form-top-ct-menu">
          <li
            v-for="(item, index) in menu"
            :key="index"
            :class="{ activeTab: index == active }"
            @click="tabNav(index)"
          >
            {{ item }}
          </li>
        </ul>
      </div>
      <div class="form-top-rt">
        <span @click="save">保存</span>
      </div>
    </div>
    <div class="form-base">
      <!-- 基础设置 -->
      <div v-show="active == 0">
        <el-form
          :model="form"
          label-width="100px"
          size="medium"
          class="demo-ruleForm form-top-ct-form"
        >
          <el-form-item label="流程名称" :required="true">
            <el-input
              v-model.trim="form.name"
              maxlength="20"
              placeholder="请输入流程名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属类型">
            <el-cascader
              style="width: 100%"
              v-model="form.formTypeId"
              :options="typeData"
              @change="handleChange"
              :props="{
                value: 'id',
                label: 'typeName',
                children: 'childList',
                expandTrigger: 'hover',
              }"
              :checkStrictly="true"
              :show-all-levels="false"
              placeholder="请选择流程类型"
              ref="typeCascader"
              clearable
              popper-class="theder"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="处理时限">
            <el-input-number
              v-model="form.expireData.expire"
              controls-position="right"
              :min="0.5"
              :max="999"
              :precision="1"
              :step="0.5"
              placeholder="请输入处理时限"
              style="width: 290px"
            ></el-input-number>
            <el-select
              v-model="form.expireData.type"
              placeholder="请选择"
              style="width: 100px; margin-left: 10px"
            >
              <el-option label="天" value="0"></el-option>
              <el-option label="小时" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流程分类">
            <el-select
              clearable
              v-model="form.workType"
              placeholder="请选择流程分类"
              :disabled="$route.query.id ? true : false"
              style="width: 100%"
            >
              <el-option label="流程类" :value="0"></el-option>
              <el-option label="指派类" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责部门">
            <el-input
              :value="arrTostr(form.unit)"
              placeholder="请选择负责部门"
              @focus="deptPanel = true"
            ></el-input>
          </el-form-item>
          <el-form-item label="自动指派" required v-if="form.workType == 1">
            <el-radio-group v-model="form.autoAllocate">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="指派给"
            required
            v-if="form.workType == 1 && form.autoAllocate == 0"
          >
            <el-input
              :value="arrTostr(form.members)"
              placeholder="请选择指派人"
              @focus="visible = true"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              type="textarea"
              v-model.trim="form.description"
              maxlength="200"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表单设计 -->
      <div v-show="active == 1" style="height: 100%">
        <create-form
          ref="form"
          :form="formConf"
          :formItem="formItem"
          :extend="extend"
        />
      </div>
      <!-- 流程设计 -->
      <div v-show="active == 2" style="height: 100%; position: relative">
        <create-flow
          :form="arr"
          :flow="processContent"
          :organization="org"
          ref="flow"
        />
      </div>
    </div>
    <!-- 部门对话框 -->
    <dept-panel
      :panelData="form.unit"
      :deptPanel="deptPanel"
      :organization="organization"
      @close="deptPanel = false"
      @save="saveDept"
    />
    <!-- 人员对话框 -->
    <user-panel-plus
      :visible="visible"
      :data="data"
      :check="checkUser"
      :defaultProps="{
        key: 'id',
        defaultParentId: '0',
        parentId: 'parentId',
        id: 'userId',
        name: 'name',
        children: 'children',
      }"
      @close="visible = false"
      @save="saveUser"
    />
  </div>
</template>

<script>
import config from '@/config'
export default {
  data() {
    return {
      settings: config.settings,
      typeData: [],
      org: {},
      organization: [],
      data: [],
      checkUser: [],
      menu: ['基础设置', '表单设计', '流程设计'],
      active: 0,
      form: {
        expireData: {
          expire: 0,
          type: '0',
        },
        unit: [],
        members: [],
      },
      deptPanel: false,
      visible: false,
      formConf: {},
      formItem: [],
      extend: {
        //表单扩展对象
        uploadUrl: '/admin/file/upload', //默认上传地址
      },
      processContent: [],
      arr: [],
      flow: [],
    }
  },
  watch: {
    active(cur) {
      if (cur === 2) {
        this.arr = this.$refs['form'].save()
          ? this.$refs['form'].save().formItem
          : []
        this.flow = this.$refs['flow'].list()
      }
    },
    'form.workType'(cur) {
      if (cur == '1') {
        this.menu = ['基础设置', '表单设计']
      } else {
        this.menu = ['基础设置', '表单设计', '流程设计']
      }
    },
  },
  created() {
    this.typeList()
    this.deptList()
    this.orgList()
    this.organizationList()
    if (this.$route.query.id) {
      this.formList()
    }
  },
  methods: {
    formList() {
      //获取表单
      this.$axios
        .get('/workorder/setting/find?id=' + this.$route.query.id)
        .then((data) => {
          if (data.code == 200) {
            this.form = data.data
            if (!data.data.expireData) {
              this.form.expireData = { expire: 0, type: '0' }
            }
            if (!data.data.unit) {
              this.form.unit = []
            }
            if (!data.data.members) {
              this.form.members = []
            }
            this.form.members.forEach((element) => {
              this.checkUser.push({
                id: '',
                name: element.name,
                userId: element.id,
              })
            })
            this.formConf = JSON.parse(data.data.form)
            this.formItem = JSON.parse(data.data.formItem)
            this.processContent = JSON.parse(data.data.processContent)
          } else {
            this.$message.error(data.msg)
          }
        })
    },
    save() {
      //保存表单
      if (!this.form.name) {
        this.$message.error('请输入流程名称')
        return
      }
      if (
        this.form.workType == 1 &&
        !this.form.autoAllocate &&
        this.form.autoAllocate != 0
      ) {
        this.$message.error('请选择是否自动指派')
        return
      }
      if (
        this.form.workType == 1 &&
        this.form.autoAllocate == 0 &&
        this.form.members.length == 0
      ) {
        this.$message.error('请选择指派人')
        return
      }
      const form = this.$refs.form.save()
      if (!form) return
      if (this.form.workType != 1) {
        const flow = this.$refs.flow.save()
        if (!flow) return
        this.form.processContent = JSON.stringify(flow)
      }
      this.form.form = JSON.stringify(form.form)
      this.form.formItem = JSON.stringify(form.formItem)
      this.$axios.post('/workorder/setting/add', this.form).then((data) => {
        if (data.code == 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.$router.push('/processCenter/allocation')
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    saveDept(data) {
      //保存部门
      this.form.unit = data
      this.deptPanel = false
    },
    saveUser(data) {
      //保存人员
      this.form.members = []
      data.forEach((element) => {
        if (element.userId != 0) {
          this.form.members.push({
            id: element.userId,
            name: element.name,
          })
        }
      })
      this.visible = false
    },
    arrTostr(data) {
      //获取名称
      const arr = []
      data.forEach((element) => {
        arr.push(element.name)
      })
      return arr.join(',')
    },
    goBack() {
      //返回
      this.$router.push('/processCenter/allocation')
    },
    tabNav(index) {
      //选中当前菜单
      this.active = index
    },
    typeList() {
      // 获取类型
      this.$axios
        .post('/workorder/configWorkOrderTypeManage/workTypeList')
        .then((data) => {
          this.typeData = []
          if (data.code == 200) {
            this.typeData = data.data
          } else {
            this.$message.error(data.msg)
          }
        })
    },
    deptList() {
      // 获取机构
      this.$axios.get('/admin/org/listTree').then((data) => {
        this.organization = []
        if (data.code == 200) {
          this.organization = data.data
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    orgList() {
      // 获取机构及人员
      this.$axios.get('/admin/org/listUnitTree').then((data) => {
        this.org = {}
        if (data.code == 200) {
          this.org = {
            organization: data.data[0],
            user: data.data[1],
          }
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    organizationList() {
      // 获取组织人员
      this.$axios.get('/admin/org/listUnitTreeV2').then((data) => {
        this.data = []
        if (data.code == 200) {
          this.data = data.data
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    handleChange(val) {
      this.$refs.typeCascader.dropDownVisible = false //监听值发生变化就关闭它
      if (val) {
        this.form.formTypeId = val[val.length - 1]
      } else {
        this.form.formTypeId = ''
      }
    },
  },
}
</script>

<style scoped>
.form {
  height: 100%;
}
.form-top {
  height: 50px;
  background: var(--active-color);
  display: flex;
}
.form-top-lt {
  width: 200px;
}
.form-top-lt p {
  height: 50px;
  line-height: 50px;
}
.form-top-lt p span {
  display: inline-block;
  width: 50px;
  height: 50px;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  text-align: center;
  margin: 0 5px 0 10px;
  border-right: 2px solid var(--theme-color);
}

.el-icon-back {
  font-size: 35px;
  margin-top: 8px;
}
.form-top-ct {
  flex: 1;
  line-height: 50px;
  text-align: center;
  font-size: 16px;
  color: #fff;
}
.form-top-rt {
  width: 200px;
  line-height: 50px;
}
.form-top-rt span {
  display: block;
  width: 67px;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  text-align: center;
  color: var(--active-color);
  border-radius: 4px;
  border: 1px solid transparent;
  background: var(--theme-color);
  cursor: pointer;
  float: right;
  margin: 10px 15px;
}
.form-top-ct-menu {
  display: block;
  width: 390px;
  margin: 0 auto;
}
.form-top-ct-menu li {
  height: 50px;
  line-height: 50px;
  font-size: 16px;
  width: 130px;
  display: inline-block;
  cursor: pointer;
}
.form-base {
  height: calc(100% - 50px);
}
.activeTab {
  background: #77dc77;
}
.form-top-ct-form {
  width: 500px;
  margin: 0 auto;
  padding-top: 60px;
}
</style>
